﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using ROrganizer.Client;
using ROrganizer.Client.Files;
using ROrganizer.UI.Controllers.Core;

namespace ROrganizer.UI.Controllers
{
    internal class RemoveSettingsFormController
    {
        private readonly string[] paths;
        private readonly FastObservableCollection<FileEntry> files;
        private readonly RemoveSettings settings;
        private RemoveTask[] tasks;

        public RemoveSettingsFormController(string[] paths)
        {
            this.paths = paths;
            this.files = new FastObservableCollection<FileEntry>();
            this.settings = ApplicationSettings.GetInstance().DefaultRemoveSettings;

            this.Refresh();
        }

        public void Refresh()
        {
            var processor = new FileProcessor();
            var query = from task in processor.PrepareToRemove(this.paths, this.settings)
                        select new FileEntry
                        {
                            Name = task.Name,
                            Size = FileEnumerator.GetFileSize(task.Files),
                            Files = task.Files.Length + task.RelatedFiles.Length,
                            Reference = task,
                        };

            this.files.Clear();
            this.files.AddRange(query.ToArray());
        }

        public bool RemoveAllAssociatedFiles
        {
            get { return this.settings.RemoveAssociatedFiles; }
            set { this.settings.RemoveAssociatedFiles = value; }
        }

        public ObservableCollection<FileEntry> Files
        {
            get { return this.files; }
        }

        public RemoveTask[] GetTasks()
        {
            return this.tasks;
        }

        public bool CanCommit()
        {
            return this.files.Any(x => x.Files > 0);
        }

        public void Commit()
        {
            var settings = ApplicationSettings.GetInstance();
            settings.DefaultRemoveSettings = this.settings;

            ApplicationSettings.Persist(settings);
            this.tasks = this.Files.Select(x => x.Reference).ToArray();
        }

        public class FileEntry
        {
            public string Name { get; set; }
            public long Size { get; set; }
            public int Files { get; set; }
            public RemoveTask Reference { get; set; }
        }
    }
}
